import csv
import math
import json  # 用于解析Json
import requests


# 提取城市经纬度
def calc_ll(x):
    # 获取自己的AK替换Post_url中 中文括号 的内容即可
    se = requests.session()  # 定义 requests 的 session 对象
    Post_url = "http://api.map.baidu.com/geocoding/v3/?address=" + x + "&output=json&ak=LPZD2Ojhsykz1kWQR8yOGOiako09EQ3q&callback=showLocation"
    Post_data = {
        'address': x
    }
    Text = se.post(Post_url, data=Post_data).text.replace("'", '"').replace('/ ', '/')[
           27:-1]  # 提取为Json格式，去掉‘showLocation&&showLocation()’这些额外的字符
    jsonValue = json.loads(Text)  # 转化为Json对象
    # print(jsonValue) # 打印Json值
    if 'result' in jsonValue:
        # print(jsonValue['result']['location']['lng'])
        # return [jsonValue['result']['location']['lng'], jsonValue['result']['location']['lat']]
        return {
            "name": x,
            "latitude": jsonValue['result']['location']['lat'],
            "longitude": jsonValue['result']['location']['lng']
        }
    else:
        return {
            "name": '异常',
            "latitude": 40.7143528,
            "longitude": -74.264324,
        }


"""
根据经纬度计算两个点之间的距离（单位：千米）
"""


def haversine_distance(lat1, lon1, lat2, lon2):
    radius = 6371  # 地球平均半径，单位：千米

    # 将角度转换为弧度
    lat1 = math.radians(lat1)
    lon1 = math.radians(lon1)
    lat2 = math.radians(lat2)
    lon2 = math.radians(lon2)

    # 计算差值
    dlat = lat2 - lat1
    dlon = lon2 - lon1

    # 应用Haversine公式计算距离
    a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    distance = radius * c

    return distance


def calculate_similarity(city1, city2):
    """
    计算城市之间的相似度，根据距离远近进行评估
    """
    lat1, lon1 = city1["latitude"], city1["longitude"]
    lat2, lon2 = city2["latitude"], city2["longitude"]

    distance = haversine_distance(lat1, lon1, lat2, lon2)
    similarity = 1000 / (1000 + distance)  # 相似度计算公式

    return similarity


def city_similarity(work_city, job_city):
    # 计算相似度
    similarities = []
    result1 = calc_ll(work_city)
    for city in job_city:
        result2 = calc_ll(city)
        similarity = calculate_similarity(result1, result2)
        if similarity >= 0.90:
            similarities.append((result2["name"], similarity))

    # 根据相似度排序结果
    similarities.sort(key=lambda x: x[1], reverse=True)
    return similarities
    # # 输出结果
    # for city, similarity in similarities:
    #     print(f"{city}: {similarity}")


def read_cities_data(file_path):
    city_data = []
    with open(file_path, 'r', encoding='utf-8') as file:
        reader = csv.DictReader(file)
        for row in reader:
            city = {
                "name": row['City'],
                "latitude": float(row['Latitude']),
                "longitude": float(row['Longitude'])
            }
            city_data.append(city)
    return city_data


# 解析城市
def get_ex_cities(city1):
    province_cities = {}
    with open('data/area_data.csv', 'r', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            province = row[0]
            city = row[1:]
            if province not in province_cities:
                province_cities[province] = []
                province_cities[province].append(city)

    for province, cities in province_cities.items():
        if city1 in cities[0]:
            ex_cities = province_cities[province][0]
            return ex_cities

    return None

# coordinates = get_city_coordinates(city)
# print(coordinates.get('latitude'))
# print(coordinates)
# work_city = input("请输入期望工作城市名字：")
# # job_city = input("请输入现在城市名字：")
# job_city = set()
# job_city.add('成都')
# job_city.add('天津')
# job_city.add('上海')
# job_city.add('大理白族自治州')
# print(job_city)
# print(city_similarity(work_city, job_city))
# jobCity = set()
#
# # 读取job_city.csv文件
# with open('data/job_city.csv', 'r', encoding='utf-8') as file:
#     reader = csv.reader(file)
#     next(reader)  # 跳过标题行
#     for row in reader:
#         jobCity.add(row[0])
#
# # 打印读取的城市数据
# for city in jobCity:
#     result = calc_ll(city)
#     with open('data/job_city.csv', 'a', newline='', encoding='utf-8') as file:
#         writer = csv.writer(file)
#         writer.writerow([result["name"], result["latitude"], result["longitude"]])
# print(len(jobCity))
# province_cities = {}
#
# with open('data/city.csv', 'r', encoding='utf-8') as file:
#     reader = csv.DictReader(file)
#     for row in reader:
#         province = row['Province']
#         city = row['City']
#         # 如果城市不为空字符串，则将其添加到相应的省份中
#         if city.strip() != '':
#             if province in province_cities:
#                 province_cities[province].add(city)
#             else:
#                 province_cities[province] = {city}
#
# # 打印省份及其对应的城市
# for province, cities in province_cities.items():
#     print(f"{province}: {', '.join(cities)}")
# province_cities = {}
# with open('data/area_data.csv', 'r', encoding='utf-8') as csvfile:
#         reader = csv.reader(csvfile)
#         for row in reader:
#             province = row[0]
#             city = row[1:]
#             if province not in province_cities:
#                 province_cities[province] = []
#                 province_cities[province].append(city)
# print(province_cities)
# print(province_cities.items)
#     # for province, cities in province_cities.items():
#     #     if city1 in cities:
#     #         return province
